package com.runfast.waimai.web.controller.Driver_controller;

import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.RunfastCuser;
import com.runfast.paotui.dao.model.RunfastShopper;
import com.runfast.paotui.service.OrderService;
import com.runfast.paotui.service.RunfastCuserService;
import com.runfast.paotui.service.RunfastShopperService;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.util.*;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/shopper/*")
public class ShopperIndexController extends DriverBaseController {
    @Resource
    OrderService orderService;
    @Resource
    private RunfastGoodsSellRecordService goodsSellRecordService;
    //RunfastGoodsSellRecord// 外卖商品订单
    @Resource
    private RunfastBusinessService businessService;
    //RunfastBusiness商家信息

    @Resource
    private RunFastSettingts runFastSettingts;
    //处理接单
    @Resource
    private RunfastShopperService shopperService;
    //骑手信息
    @Resource
    private RunfastGoodsSellOutStatusService goodsSellOutStatusService;
    // 外卖商品配送状态
    @Resource
    private RunfastTransorderService transOrderService;
    //转单信息

    @Resource
    private RunfastGoodsSellChildrenService goodsSellRecordChildrenService;
    /// 外卖商品订单记录子类

    @Resource
    private RunfastCreditlevelService creditLevelService;
    //信用等级管理
    private RunfastCuserService cuserService;
    ////用户信息
    /**
     * ȡ取货
     */
    @RequestMapping(value="ordertake",method=RequestMethod.POST)//验证֤
    public @ResponseBody ModelMap ordertake( String orderCode,String token){ //骑手id
        ModelMap model = new ModelMap();
      //   msg ="参数错误";
         //isSuccess = false;
        if(super.getLoginShopper(token)!=null&&orderCode!=null){
     //  	RunfastGoodsSellRecord gr = goodsSellRecordService.findByShopperIdAndOrderCode(1,orderCode);//测试orderCode为123
          Order gr = orderService.findByShopperidAndCode(super.getLoginShopper(token).getId(),orderCode);//通过骑手ID ,定单号获得外卖商品规格 super.getLoginShopper().getId()
            // 外卖商品订单
            if(!gr.getDriverId().equals(super.getLoginShopper(token).getId())){
                String   msg ="该订单为其他骑手订单";
                model.put("msg", msg);
            }
            if(gr!=null){
                //  0  created=下单成功 1canceled=取消订单  2paid=接单成功 3taken=排列 4completed==订单完成
                if(gr.getStatus()==Order.Status.CREATED){
                    ////订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
                    if(gr.getCanceled()!=null&&gr.getCanceled()==true){///用户申请取消订单
                        String      msg = "用户申请取消该订单，请等待商家审核!";
                        model.put("msg", msg);
                    }else{
                        if(gr.getStatus()==Order.Status.CREATED){
                 //           RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();//  外卖商品配送状态

                      //      goodsSellOutStatus.setBusinessid(gr.getBusinessid());//商家ID
                      //      goodsSellOutStatus.setBusinessname(gr.getBusinessname());//商家 名称
//                            goodsSellOutStatus.setCreatetime(new Date());//状态时间
//                            goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());//设置定单号
//                            goodsSellOutStatus.setGoodssellrecordid(gr.getId());//设置外卖商品id
//                            goodsSellOutStatus.setSort(4);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
//                            goodsSellOutStatus.setType(2);//  操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户,4:代理商
//                            goodsSellOutStatus.setStatstr("商品打包");
//                            RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
//                            if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(4))){
//                                ////   sort 订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
//                                goodsSellOutStatusService.save(goodsSellOutStatus);
//                            }
                        }
                        gr.setStatus(Order.Status.PAID);//设置为配送状态

                        orderService.updateByPrimaryKeySelective(gr);//更新状态
                        //订单状态操作记录
//                        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();//  外卖商品配送状态
//
//                        goodsSellOutStatus.setCreatetime(new Date());
//                        goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());
//                        goodsSellOutStatus.setGoodssellrecordid(gr.getId());
//                        goodsSellOutStatus.setOperationid(super.getLoginShopper().getId());
//                        goodsSellOutStatus.setOperationname(super.getLoginShopper().getName());
//                        goodsSellOutStatus.setSort(5);
//                        goodsSellOutStatus.setStatstr("商品配送");
//                        goodsSellOutStatus.setType(2);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
//                        RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);////  外卖商品配送状态
//                        if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(5))){
//                            goodsSellOutStatusService.save(goodsSellOutStatus);
//                        }
                        boolean   isSuccess = true;
                        String     msg = "货物已代购配送中!";
                        model.put("msg", msg);

                        model.put("success", isSuccess);
                    }

                }
            }else{
                String    msg ="请先签到再取！";
                model.put("msg", msg);

            }


        }

     //
        return model;
    }
    //**********************************************************************************************下面为抢单简写
    //抢单1
    @PostMapping("orderfight1")
    public @ResponseBody ModelMap orderfight1(Integer id,String token){//订单id号,id1为骑手id
        ModelMap  model =new ModelMap();
        // msg="参数错误";
        boolean isSuccess=false;
        if(super.getLoginShopper(token)!=null&&id!=null){
            int size=0;
            RunfastShopper runfastShopper=shopperService.get(super.getLoginShopper(token).getId());
            Integer num=runfastShopper.getDistributionmun();//  配送最大数量默认为5
//            if(num==null){
//                num=5;
//            }
            List<Order>glist=orderService.findByShopperid(super.getLoginShopper(token).getId());//通过骑手ID 获得手上跑腿订单信息集合
            List<RunfastGoodsSellRecord> list1= goodsSellRecordService.findById(super.getLoginShopper(token).getId());
            if(glist!=null){
                size=glist.size(); //获得骑手手上的订单的数量
            }
            if((size+list1.size())<(num+1)){ //别忘记加1
                if(!runFastSettingts.hasTakeThatOrderId(id)){ // * 判断是否有人正在执行该订单的接单操作定单 order的id
                    runFastSettingts.addTakeThatOrderId(id);//添加正在接单操作的订单id
                    Order gr = orderService.get(id);//订单ID 获得订单信息
                    if(gr!=null&&gr.getDriverId()==null&&gr.getStatus()!=null&&(gr.getStatus()==Order.Status.CREATED)) {
                        //1：客户已付款
                      //设置骑手id
                        //订单状态操作记录
//                        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
////                        goodsSellOutStatus.setBusinessid(gr.getBusinessid());
////                        goodsSellOutStatus.setBusinessname(gr.getBusinessname());
//                        goodsSellOutStatus.setCreatetime(new Date());
//                        goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());
//                        goodsSellOutStatus.setGoodssellrecordid(gr.getId());
//                        goodsSellOutStatus.setOperationid(super.getLoginShopper().getId());
//                        goodsSellOutStatus.setOperationname(super.getLoginShopper().getName());
//                        goodsSellOutStatus.setSort(3);
              //          if(gr.getStatus()==Order.Status.PAID){
                            //  gr.setStype(1);
                    //        goodsSellOutStatus.setStatstr("骑手已接单");
             //           }else{
            //                gr.setStatus(Order.Status.CREATED);//骑手接单
                  //          goodsSellOutStatus.setStatstr("骑手代购中");
                 //       }

              //          goodsSellOutStatus.setType(2);;//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
           //             orderService.updateByPrimaryKeySelective(gr);


               //         RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
                //        if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(3))){
                            ////sort    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
                  //          goodsSellOutStatusService.save(goodsSellOutStatus);
                //        }
                        //RunfastGoodsSellRecord grtemp = goodsSellRecordService.get(id);// 外卖商品规格
                        Order grtemp=orderService.get(id);
                        if(grtemp != null &&  grtemp.getDriverId()==null)  //骑手账号为空， 更新订单
                        {   gr.setDriverId(super.getLoginShopper(token).getId());
                            orderService.updateByPrimaryKeySelective(gr);
                            String    msg = "抢单成功";
                            model.put("msg", msg);
                        }else{
                      String     msg="订单已经被抢走一";
                            model.put("msg", msg);
                        }
                        isSuccess = true;
                    }else{
                        String   msg = "该订单已被抢走二!";
                        model.put("msg", msg);
                    }
                    runFastSettingts.removeTakeThatOrderId(id);//删除正在接单操作的订单id
                }else{
                    String  msg = "该订单已被抢走三!";
                    model.put("msg", msg);
                }
             }else{
                String    msg = "未完成订单已达上限，请先完成手上订单!";
                model.put("msg", msg);
            }

            model.put("success", isSuccess);

                     }

        return  model;
            }


  //*****************************************************************************************************************************^^^^^^^^^^^^
    /**
     * 抢单
     */
    @RequestMapping(value="orderfight",method=RequestMethod.POST)///验证
    public @ResponseBody ModelMap orderfight(@RequestParam(value="id",required=false) Integer id,String token){ //定单ID

        ModelMap model = new ModelMap();
        String msg ="参数错误";
        boolean isSuccess = false;
        if(super.getLoginShopper(token)!=null&&id!=null){
            RunfastShopper runfastShopper=super.getLoginShopper(token);
            int size=0;
            Integer num=runfastShopper.getDistributionmun();//  配送最大数量
            if(num==null){
                num=5;
            }
            List<RunfastGoodsSellRecord> list1= goodsSellRecordService.findById(runfastShopper.getId());
            List<Order>glist=orderService.findByShopperid(runfastShopper.getId());//通过骑手ID 获得手上跑腿订单信息集合
            // 外卖商品订单
            if(glist!=null){
                size=glist.size(); //获得骑手手上的订单的数量
            }
            if((size+list1.size())<num+1){ //小于5+1，说明还可以接单
                if(!runFastSettingts.hasTakeThatOrderId(id)){ // * 判断是否有人正在执行该订单的接单操作定单
                    runFastSettingts.addTakeThatOrderId(id);//添加正在接单操作的订单id

                    Order gr = orderService.get(id);//订单ID 获得订单信息
                    if(gr!=null&&gr.getDriverId()==null&&gr.getStatus()!=null&&(gr.getStatus()==Order.Status.CREATED)){//1：客户已付款
                        gr.setDriverId(super.getLoginShopper(token).getId());//设置骑手id
                       //  gr.setdriv(super.getLoginShopper().getName());//设置骑手名字
                       // gr.setShoppermobile(super.getLoginShopper().getMunber());//设置骑手 的手机号

                        RunfastCreditlevel c=null;// // 信用等级管理
                        if(runfastShopper.getCreditLevelid()!=null){
                            c=creditLevelService.get(runfastShopper.getCreditLevelid());//查看信誉等级情况
                        }else{
                            List<RunfastCreditlevel> list=  creditLevelService.findAll();//  信用等级管理
                            if(list!=null&&list.size()>0){
                                c=list.get(0);
                            }
                        }

                        if(c!=null){
                            BigDecimal shopperMoney=BigDecimal.valueOf(0);
                            if(c.getStartTimeDay()!=null && c.getEndTimeDay()!=null){
                                Calendar calendar = Calendar.getInstance();
                                int hour = calendar.get(Calendar.HOUR_OF_DAY);


                                calendar.setTime(c.getStartTimeDay());
                                int startTime1 = calendar.get(Calendar.HOUR_OF_DAY);
                                calendar.setTime(c.getEndTimeDay());
                                int endTime1 = calendar.get(Calendar.HOUR_OF_DAY);
                                if(MyUtil.inTime(c.getStartTimeDay(), c.getEndTimeDay(), new Date())){//符合第一时段配送费
                                    shopperMoney=c.getCommissionDay();

                                }else{
                                    shopperMoney=c.getCommissionNight();
                                }
                                if(shopperMoney==null){
                                    shopperMoney=BigDecimal.valueOf(0);
                                }
                                if(gr.getDistance()!=null){
                                    if(gr.getDistance()!=null&&c.getDistan()!=null&&c.getPrice()!=null){//distan超出多少公里后额外加钱
                                        Double distan=c.getDistan();
                                        if(Double.parseDouble(String.valueOf(gr.getDistance()))>distan*1000){//当超出了范围后，计算超出的费用
                                            double ss =  Double.parseDouble(String.valueOf(gr.getDistance())) - distan*1000;
                                            ss = ss /1000;
                                            if(ss%1!=0){
                                                ss=  ss+1;
                                            }
                                            int sd = (int)ss;
                                            BigDecimal priceshopper = c.getPrice().multiply(BigDecimal.valueOf(sd));  //额外每公里加多少钱
                                            shopperMoney=shopperMoney.add(priceshopper);
                                            if(c.getMaxprice()!=null){
                                                if(shopperMoney.compareTo(c.getMaxprice())==1){
                                                    shopperMoney = c.getMaxprice();
                                                }
                                            }
                                        }
                                    }
                                }
                            //    gr.setShoppermoney(shopperMoney);
                            }
                        }


                        //订单状态操作记录
                        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
//                        goodsSellOutStatus.setBusinessid(gr.getBusinessid());
//                        goodsSellOutStatus.setBusinessname(gr.getBusinessname());
                        goodsSellOutStatus.setCreateTime(new Date());
                        goodsSellOutStatus.setGoodsSellRecordCode(gr.getOrderNo());
                        goodsSellOutStatus.setGoodsSellRecordId(gr.getId());
                        goodsSellOutStatus.setOperationId(super.getLoginShopper(token).getId());
                        goodsSellOutStatus.setOperationName(runfastShopper.getName());
                        goodsSellOutStatus.setSort(3);
                        if(gr.getStatus()==Order.Status.PAID){
                            //    created=下单成功 canceled=取消订单  paid=接单成功 taken=排列 completed==订单完成
                          //  gr.setStype(1);
                            goodsSellOutStatus.setStatStr("骑手已接单");
                        }else{
                            gr.setStatus(Order.Status.CREATED);//骑手接单
                            goodsSellOutStatus.setStatStr("骑手代购中");
                        }

                        goodsSellOutStatus.setType(2);;//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
                        msg = "抢单成功";

                        RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
                        if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(3))){
                            ////sort    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
                            goodsSellOutStatusService.save(goodsSellOutStatus);
                        }
                        //RunfastGoodsSellRecord grtemp = goodsSellRecordService.get(id);// 外卖商品规格
                        Order grtemp=orderService.get(id);
                        if(grtemp != null &&  grtemp.getDriverId()==null)
                        {
                            orderService.updateByPrimaryKeySelective(gr);
                        }else{
                            msg="订单已经被抢走一";
                        }
                        isSuccess = true;
                    }else{
                        msg = "该订单已被抢走二!";
                    }
                    runFastSettingts.removeTakeThatOrderId(id);//删除正在接单操作的订单id
                }else{
                    msg = "该订单已被抢走三!";
                }
            }else{
                msg = "未完成订单已达上限，请先完成手上订单!";
            }

        }
        model.put("msg", msg);
        model.put("success", isSuccess);
        return model;
    }
    /**
     * 送达
     */
    @RequestMapping(value="orderarrived",method=RequestMethod.POST)//验证
    public @ResponseBody ModelMap orderarrived(String orderNo,String token){
        ModelMap model = new ModelMap();
       String msg ="成功送达";
        boolean isSuccess = true;
        if(super.getLoginShopper(token)!=null&&orderNo!=null){
        //    Order gr = orderService.findByShopperidAndCode(1,orderNo);//这个是测试用，呆会要改过来
          Order gr = orderService.findByShopperidAndCode(super.getLoginShopper(token).getId(),orderNo);
            if(gr!=null&&gr.getStatus()!=null&&gr.getStatus()==Order.Status.PAID){
                //    created=下单成功 canceled=取消订单  paid=接单成功 taken=排列 completed==订单完成

                gr.setTaken(true);//设定为已收货
                gr.setStatus(Order.Status.COMPLETED);//订单完成
            //    gr.setStatstr("订单完成");//订单完成
            //    gr.setReadytime(new Date());//订单完成时间
                orderService.updateByPrimaryKeySelective(gr);///更新数据跑腿商品订单记录
                //	goodsSellService.updateSalesnum(gr);//// 更新外卖商品
//              goodsSellRecordChildrenService.updateFindByPid(gr.getId(),4);//执行定单更新和返回INT
//
//                //订单状态操作记录
//                RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
//             /*   goodsSellOutStatus.setBusinessid(gr.getBusinessid());//设置商家ID
//                goodsSellOutStatus.setBusinessname(gr.getBusinessname());//设置商家名字*/
//                goodsSellOutStatus.setCreatetime(new Date());//设置订单时间
//                goodsSellOutStatus.setGoodssellrecordcode(gr.getOrderNo());//设置订单号
//                goodsSellOutStatus.setGoodssellrecordid(gr.getId());////商品订单ID
//                goodsSellOutStatus.setOperationid(super.getLoginShopper().getId());//设置骑手ID
//                goodsSellOutStatus.setOperationname(super.getLoginShopper().getName());//设置骑手姓名
//                goodsSellOutStatus.setSort(8);//    订单状态编码 -1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成，11:骑手到达
//                goodsSellOutStatus.setStatstr("订单完成");
//                goodsSellOutStatus.setType(2);///操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户
//                RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrderNo(), null);
//                //  RunfastGoodsSellOutStatus goodsSellOut = goodsSellOutStatusService.findsortandGoodsSellRecordCode(gr.getOrdercode(), 2);
//                if(goodsSellOut==null||(goodsSellOut.getSort()!=null&&!goodsSellOut.getSort().equals(8))||goodsSellOut.getSort()==null){
//                    goodsSellOutStatusService.save(goodsSellOutStatus);
//                }
//             /
                RunfastCuser cuser=cuserService.get(gr.getCuserId());

                HashMap<String, String> params = new HashMap<>();
                params.put("orderCode", gr.getOrderNo());
                MsgPushUtils.pushToUser(10,params,"送达提醒","您的代购订单:"+gr.getOrderNo()+"已经送达",cuser.getAlias());

                    msg = "配送成功!";

                isSuccess = true;
            }

        }
        model.put("msg", msg);
        model.put("success", isSuccess);
        return model;
    }

}
